<?php
namespace Icsoc\DataBundle\Model;

use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Icsoc\CoreBundle\Logger\ActionLogger;

/**
 * 下面中用到info参数的json格式大概为 ；filter搜素(具体提供搜素字段各个接口不一样)，
 *  pagination分页(rows 每页显示条数,page第几页)，sort排序
 *  {"pagination":{"rows":20,"page":"5"},"filter":{"endresult":"0"},"sort":{"field":"id","order":"desc"}}
 * Class BillModel
 * @package Icsoc\DataBundle\Model
 *
 */
class WhiteModel extends BaseModel
{

    /** @var \Symfony\Component\DependencyInjection\Container  */
    public $container;

    /** @var \Doctrine\DBAL\Connection  */
    private $dbal;

    //分机类型
    private $phoneType;

    /**
     * @param ContainerInterface $container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
        $this->dbal = $this->container->get('doctrine.dbal.default_connection');
        $this->phoneType = $this->container->getParameter('phone_type');
    }

    /**
     * 语音列表
     * @param array $param 参数，格式为
     *                     array(
     *                         vcc_code,//企业代码
     *                         info,// array 提供分页信息
     *                     )
     * @return array
     */
    public function getWhiteList(array $param = array())
    {
        $vcc_code = empty($param['vcc_code']) ? 0 : $param['vcc_code'];
        $vid = empty($param['vcc_id']) ? 0 : $param['vcc_id'];
        $info = empty($param['info']) ? '' : $param['info'];
        //分页搜索相关信息；
        $addInfo = array();
        if (!empty($info)) {
            $addInfo = json_decode($info, true);
            if (json_last_error()) {
                return array('code' => 405, 'message'=>'info格式非json');
            }
        }

        $msg = $vid = $this->container->get('icsoc_data.validator')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        $where = '';
        if (isset($addInfo['filter'])) {
            if (isset($addInfo['filter']['keyword']) && !empty($addInfo['filter']['keyword'])) {
                $where.=" AND (phone_num  LIKE '%".$addInfo['filter']['keyword']."%'
                OR trunk_num LIKE '%".$addInfo['filter']['keyword']."%' ) ";
            }
        }
        $count = $this->dbal->fetchColumn(
            "SELECT count(*)
            FROM cc_whitelist
            WHERE vcc_id = :vid ".$where,
            array('vid'=>$vid)
        );
        $page = $this->container->get("icsoc_data.helper")->getPageInfo($count, 'cc_whitelist', $addInfo);
        $data = $this->dbal->fetchAll(
            "SELECT id,vcc_id,phone_num,trunk_num FROM cc_whitelist WHERE vcc_id= :vid ".$where.
            'ORDER BY '.$page['sort'].' '.$page['order'].' LIMIT '.$page['start'].','.$page['limit'],
            array('vid'=>$vid)
        );
        $ret = array(
            'code' => 200,
            'message' => 'ok',
            'total' => $count,
            'page' => $page['page'],
            'totalPage'=>$page['totalPage'],
            'data' => $data
        );
        return $ret;
    }

    /**
     * 删除白名单
     * @param array $param vcc_id 企业id或者 vcc_code 企业代码， ids 删除的id 多个用,隔开（1,2,3）
     * @return array|string
     */
    public function delWhite(array $param = array())
    {
        $vcc_code = empty($param['vcc_code']) ? 0 : $param['vcc_code'];
        $phone_ids = empty($param['ids']) ? '' : $this->purifyHtml(is_string($param['ids']) ? $param['ids'] : '');

        $msg = $vcc_id = $this->container->get('icsoc_data.validator')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        if (empty($phone_ids)) {
            $ret = array(
                'code' => 407,
                'message' => '号码ID为空'
            );
            return $ret;
        }

        $this->dbal->beginTransaction();
        $phonesArray = explode(',', $phone_ids);
        $logStr = "";
        foreach ($phonesArray as $phone_id) {
            if (!is_numeric($phone_id)) {
                $ret = array(
                    'code' => 403,
                    'message' => '号码ID中包含非数字字符'
                );
                return $ret;
            }
            $data = array(
                'vcc_id' => $vcc_id,
                'id' => $phone_id,
            );
            $logStr.=$data['id'].',';
            $this->dbal->delete('cc_whitelist', $data);
        }
        try {
            $this->dbal->commit();
            $ret = array(
                'code' => 200,
                'message' => 'ok'
            );
            if (!empty($logStr)) {
                $logStr = $this->container->get('translator')
                    ->trans('Delete white list %str%', array('%str%'=>$logStr));
                $this->container->get('icsoc_core.helper.logger')->actionLog(ActionLogger::ACTION_DELETE, $logStr);
            }
            return $ret;
        } catch (Exception $e) {
            $this->dbal->rollback();
            $ret = array(
                'code' => 404,
                'message' => '删除白名单失败['.$e->getMessage().']'
            );
            return $ret;
        }
    }

    /**
     * @param array $param
     *      vcc_id 企业id或者
     *      vcc_code 企业代码，
     *      phones array黑名单号码，
     *      trunk_num  中继号码；空为所有，
     * @return array|string
     *
     */
    public function whiteAdd(array $param = array())
    {
        $vcc_code = isset($param['vcc_code']) && !empty($param['vcc_code']) ? $param['vcc_code'] : 0;
        $phones = isset($param['phones']) && !empty($param['phones']) ? $param['phones'] : array();
        $trunk_num = isset($param['trunk_num']) && !empty($param['trunk_num']) ? $param['trunk_num'] : '';
        $white_sound = isset($param['white_sound']) && !empty($param['white_sound']) ? $param['white_sound'] : '';

        $msg = $vcc_id = $this->container->get('icsoc_data.validator')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        if (empty($phones)) {
            $ret = array(
                'code' => 405,
                'message' => '号码为空'
            );

            return $ret;
        }

        if (!is_array($phones)) {
            $ret = array(
                'code' => 406,
                'message' => '号码格式不对，要求为逗号隔开的字符',
            );
            return $ret;
        }

        if (empty($trunk_num)) {
            $ret = array(
                'code' => 407,
                'message' => '中继号码为空'
            );
            return $ret;
        }
        if (!empty($trunk_num)) {
            //查看中继号是否存在
            $count = $this->dbal->fetchColumn(
                'SELECT count(*) FROM cc_phone400s WHERE vcc_id = :vcc_id AND phone = :phone ',
                array('vcc_id'=>$vcc_id, 'phone'=>$trunk_num)
            );
            if ($count <= 0) {
                return array('code'=>410, 'message'=>'中继号码不存在');
            }
        }
        $this->dbal->beginTransaction();
        $phones = array_unique($phones);
        $logStr = '';
        foreach ($phones as $phone) {
            if (!is_numeric(trim($phone))) {
                $ret = array(
                    'code' => 408,
                    'message' => '号码中包含非数字字符'
                );
                return $ret;
            }
            $data = array(
                'vcc_id' => $vcc_id,
                'phone_num' => trim($phone),
                'trunk_num' => $trunk_num,
            );
            $count = $this->dbal->fetchColumn(
                "SELECT count(*) FROM cc_whitelist
                WHERE vcc_id = :vcc_id AND phone_num = :phone_num AND trunk_num = :trunk_num",
                $data
            );
            if ($count) {
                continue;
            }
            $logStr.=$data['phone_num'].',';
            $this->dbal->insert('cc_whitelist', $data);
        }
        if (!empty($white_sound)) {
            //修改配置；
            $sound = $this->dbal->fetchAssoc(
                "SELECT address,sounds_address FROM win_sounds WHERE id = :id",
                array('id'=>$white_sound)
            );
            if (!empty($sound)) {
                $data = array('white_sound'=>$sound['address'],'white_sound_address'=>$sound['sounds_address']);
                $this->dbal->update("cc_ccod_configs", $data, array('vcc_id'=>$vcc_id));
            }
        }
        try {
            $this->dbal->commit();
            $ret = array(
                'code' => 200,
                'message' => 'ok'
            );
            if (!empty($logStr)) {
                $logStr = $this->container->get('translator')->trans('Add white list %str%', array('%str%'=>$logStr));
                $this->container->get('icsoc_core.helper.logger')->actionLog(ActionLogger::ACTION_ADD, $logStr);
            }
            return $ret;
        } catch (Exception $e) {
            $this->dbal->rollback();
            $ret = array(
                'code' => 409,
                'message' => '添加白名单失败['.$e->getMessage().']'
            );
            return $ret;
        }
    }
}
